package org.example.service.impl;

import com.jiutianjia.auth.dto.LoginDto;
import com.jiutianjia.auth.entity.LoginUser;
import com.jiutianjia.auth.entity.MemberEntity;
import com.jiutianjia.auth.utils.JwtUtil;
import com.jiutianjia.exception.JtjException;
import com.jiutianjia.member.enums.ResponseCodeEnum;
import com.jiutianjia.member.utils.RedisUtils;
import com.jiutianjia.member.utils.ResultData;
import org.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Description: 实现类
 * Author: 乔包包
 * Date: 2023/11/25
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public ResultData login(LoginDto loginDto) throws JtjException {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getPhone(),loginDto.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if(ObjectUtils.isEmpty(authentication)){
            throw new JtjException(ResponseCodeEnum.LOGIN_AUTH);
        }
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        MemberEntity memberEntity = principal.getMemberEntity();
        RedisUtils.put("USER_"+memberEntity.getId(),principal);
        String token = jwtUtil.generateToken(principal);
        Map<String,String> res = new HashMap<>();
        res.put("token",token);
        return ResultData.success(res);
    }
}
